# application/mapper/system/user.py
from application.extensions.databases import db
from application.models.system.user import SysUser
from typing import List, Dict, Any
from application.extensions.logging import system_logger

class UserMapper:
    """用户数据访问层"""
    
    @staticmethod
    def get_user_list(page_num: int, page_size: int, conditions: Dict[str, Any] = None) -> tuple:
        """
        分页查询用户列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: (用户列表, 总数)
        """
        try:
            # 构建查询
            query = db.session.query(SysUser)
            
            # 添加查询条件
            if conditions:
                if conditions.get('userName'):
                    query = query.filter(SysUser.user_name.like(f"%{conditions['userName']}%"))
                if conditions.get('nickName'):
                    query = query.filter(SysUser.nick_name.like(f"%{conditions['nickName']}%"))
                if conditions.get('phonenumber'):
                    query = query.filter(SysUser.phonenumber.like(f"%{conditions['phonenumber']}%"))
                if conditions.get('status'):
                    query = query.filter(SysUser.status == conditions['status'])
                # 注意：您的用户模型中没有 create_time 字段，所以注释掉时间查询
                if conditions.get('beginTime') and conditions.get('endTime'):
                    query = query.filter(SysUser.create_time >= conditions['beginTime'])
                    query = query.filter(SysUser.create_time <= conditions['endTime'])
                elif conditions.get('beginTime'):
                    query = query.filter(SysUser.create_time >= conditions['beginTime'])
                elif conditions.get('endTime'):
                    query = query.filter(SysUser.create_time <= conditions['endTime'])
            
            # 获取总数
            total = query.count()
            
            # 分页查询
            offset = (page_num - 1) * page_size
            users = query.offset(offset).limit(page_size).all()
            
            return users, total
            
        except Exception as e:
            system_logger.error(f"查询用户列表失败: {e}")
            raise e
        




    @staticmethod
    def get_user_by_username(username: str) -> SysUser:
        """
        根据用户名获取用户
        :param username: 用户名
        :return: 用户对象
        """
        user = db.session.query(SysUser).filter(SysUser.user_name == username).first()
        return user
        